package cn.mastercom.gui.hdfsExplorer.views;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.*;

import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.tree.TreePath;

import cn.mastercom.common.util.ArraysUtil;
import lombok.extern.log4j.Log4j;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.Logger;

import cn.mastercom.bigdata.util.CalendarEx;
import cn.mastercom.gui.components.CustomDialog;
import cn.mastercom.gui.components.RowHeaderTable;
import cn.mastercom.gui.util.GuiUtil;
import cn.mastercom.sssvr.util.HdfsExplorerHelper;
import cn.mastercom.sssvr.util.HdfsExplorerHelper.GotoPathCmd;

@Log4j
public class TablePane extends JScrollPane implements Observer {

	private static final long serialVersionUID = 1L;

	private JTable table;
	private JTextField filterField;
	private JLabel filterDetail;
	private transient HdfsExplorerHelper helper;

	private String tempFileName; // 文件名
	private String tempFilesize; // 文件大小
	private String tempDir; // 文件目录
	private boolean tempIsDir; // 是否目录
	private String tempPath; // 路径
	private String tempParentPath; // 父路径
	private String tempFileDate; // 文件最后修改时间

    private JComboBox  jcb;

	public TablePane(HdfsExplorerHelper helper) {

		this.table = new JTable();
		this.helper = helper;
		helper.addObserver(this);

		initUI();
		initLookAndFeel();

		addEventListener();
		addActionListener();
	}

	/**
	 * 延迟绑定事件
	 */
	public void setFilterField(JTextField filterField) {
		this.filterField = filterField;
		this.filterField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					setRowHeaderView(null);
					filterRow(TablePane.this.filterField.getText());
					if (table.getRowCount()!=0)
						setRowHeaderView(new RowHeaderTable(table));
				}
			}
		});
	}

	public void setFilterDetail(JLabel filterDetail) {
		this.filterDetail = filterDetail;
	}

	/**
	 * 初始化表格视图的数据模型
	 */
	private void initUI() {

		String[] row = { ""/* icon */, "文件", "大小", "用户与权限", "路径", "父路径", "最后修改日期", "文件大小排序(KB)" };

		DefaultTableModel tableModel = new DefaultTableModel(new Object[][] {}, row) {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}

			@Override
			public Class<?> getColumnClass(int column) {
				try {
					if (getRowCount() <= 1) {
						return int.class;
					} else {
						return getValueAt(0, column).getClass();
					}
				} catch (Exception e) {
				    log.error(e);
				}
				return int.class;
			}
		};
		table.setModel(tableModel);
		setViewportView(table);
	}

	/**
	 * 初始化表格视图的样式与风格
	 */
	private void initLookAndFeel() {
		helper.initLookAndFeel();
		// 设置表格列宽
		table.getColumnModel().getColumn(0).setMaxWidth(20);
		table.getColumnModel().getColumn(0).setMinWidth(20);

		// 通过点击表头来排序列中数据resort data by clicking table header
		TableRowSorter<TableModel> sorter = new TableRowSorter<>(table.getModel());

		table.setRowSorter(sorter);
		table.setRowHeight(20);// 20

		// 第一列渲染为图标
		table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
			private static final long serialVersionUID = 1L;

			@Override
			public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
					boolean hasFocus, int row, int column) {
				if (value instanceof Icon) {
					this.setIcon((Icon) value);
					this.setText("");
				}
				return this;
			}
		});

		// 第三列（大小）右对齐
		DefaultTableCellRenderer render = new DefaultTableCellRenderer();
		render.setHorizontalAlignment(JLabel.RIGHT);
		table.getColumnModel().getColumn(2).setCellRenderer(render);

		GuiUtil.hideTableColumn(table, 4);// 隐藏---路径
		GuiUtil.hideTableColumn(table, 5);// 隐藏---父路径
	}

	/**
	 * 添加表格控件监听事件
	 */
	private void addEventListener() {
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {// 点击几次，这里是双击事件
					tableDbClick();
				}
			}
		});
	}

	private void addActionListener() {
        String[] dirMenuItems = {"从HDFS下载", "归并压缩下载", "新建文件夹", "上传文件", "解压上传文件", "上传文件夹", "归并上传文件夹", "|", "合并小文件", "添加SUCCESS标志文件", "|", "删除", "重命名", "批量重命名该文件夹下文件", "过滤", "剪切", "复制", "粘贴", "复制完整名称", "复制表信息", "返回上一级"};
        String[] fileMenuItems = {"从HDFS下载", "下载5MB", "新建文件夹", "上传文件", "上传文件夹", "|", "删除", "重命名", "剪切", "复制", "|", "预览", "复制完整名称", "复制表信息", "返回上一级"};
        String[] dirAndFileMenuItems = {"从HDFS下载", "|", "删除", "剪切", "复制", "复制完整名称", "复制表信息", "返回上一级"};
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(final MouseEvent e) {
                if (!e.isPopupTrigger()) return;

                int[] rows = table.getSelectedRows();
                boolean haveFile = false;
                boolean haveDir = false;
                if (rows.length <= 1) {
                    int rowAtPoint = table.rowAtPoint(table.getMousePosition());
                    table.setRowSelectionInterval(rowAtPoint, rowAtPoint);
                    getTableInfoByRow(rowAtPoint);
                    if (tempIsDir) haveDir = true;
                    else haveFile = true;
                } else {
                    for (int row : rows) {
                        getTableInfoByRow(row);
                        if (tempIsDir) haveDir = true;
                        else haveFile = true;
                        if (haveFile && haveDir) break;
                    }
                }
                String[] items;
                if (haveDir && haveFile) items = dirAndFileMenuItems;
                else if (haveDir) items = dirMenuItems;
                else items = fileMenuItems;
                JPopupMenu popupMenu = new JPopupMenu();
                for (String text : items) {
                    if (text.equals("|")) {
                        popupMenu.addSeparator();
                    } else {
                        JMenuItem menuItem = new JMenuItem(text);
                        menuItem.addActionListener(popupTableListener());
                        popupMenu.add(menuItem);
                    }
                }
                popupMenu.show(e.getComponent(), e.getX(), e.getY());
            }
        });
    }

	/**
	 * tablePanel的双击事件：打开文件夹
	 */
	private void tableDbClick() {
		int row = table.getSelectedRow();
		getTableInfoByRow(row);// 提取 tempPath

		if (!tempIsDir) {
			helper.previewFile(tempPath);
			return;
		}
		// 让观察者通知所有被观察者更新数据
		// helper.notification(tempPath);
		helper.executeCmd(new GotoPathCmd(tempPath, helper));
	}

	/**
	 * 从tableModel中获取文件/文件夹信息
	 */
	private void getTableInfoByRow(int row) {
		tempFileName = getValue(row, 1);
		tempFilesize = getValue(row, 2);
		tempDir = getValue(row, 3);
		if (tempDir.indexOf("目录") > -1) {
			tempIsDir = true;
		} else {
			tempIsDir = false;
		}
		// String tempPath = getValue(row,2);
		tempPath = getValue(row, 4);
		tempParentPath = getValue(row, 5);
		tempFileDate = getValue(row, 6);
	}

	/**
	 * 从tableModel的单元格中信息
	 */
	private String getValue(int row, int column) {
		return table.getModel().getValueAt(table.convertRowIndexToModel(row), column).toString();// 方法1：获取排序后实际行号值
	}

	/**
	 * 添加数据到表格里
	 */
	private void addRowForTable(Object[][] fileList) {
		try {
			// 去掉行号
			this.setRowHeaderView(null);
			DefaultTableModel model = ((DefaultTableModel) table.getModel());
			model.setRowCount(0);
            for (Object[] aFileList : fileList) {
                model.addRow(aFileList);
            }
			// 添加行号
			if (table.getRowCount()!=0)
				this.setRowHeaderView(new RowHeaderTable(table));
		} catch (Exception e) {
		    log.error(e);
        }
	}

	/**
	 * 刷新表格信息（根据已有数据）
	 * 
	 * @param fileList
	 *            传入的数据
	 */
	public void refreshTable(final FileStatus[] fileList) {
		Object[][] list = fu(fileList);
		addRowForTable(list);
	}

	/**
	 * 根据文件状态信息转换JTableModel的信息
	 */
	private Object[][] fu(FileStatus[] file) {

		Object[][] m = new Object[file.length][8];// 增加文件路径，父路径

		for (int i = 0; i < file.length; i++) {
			setTableCellContentAt(m, file[i], i);
		}
		return m;
	}

	/**
	 * 更改表格单元内容
	 */
	private void setTableCellContentAt(Object[][] m, FileStatus file, int row) {
		m[row][1] = file.getPath().getName();
		if (file.isDirectory()) {
			long fileLen = helper.getFileSize(file.getPath());
			m[row][0] = helper.getSystemIcon(file.getPath().getName(), file.isDirectory());
			m[row][2] = helper.getFileLengthDesc(fileLen);
			m[row][3] = "目录[" + file.getOwner() + " " + file.getPermission().toString() + "]";
			m[row][7] = helper.getFileLengthDescByKB(fileLen);
		} else {
			m[row][0] = helper.getSystemIcon(file.getPath().getName(), file.isDirectory());
			m[row][2] = helper.getFileLengthDesc(file.getLen());
			m[row][3] = "文件[" + file.getOwner() + " " + file.getPermission().toString() + "]";
			m[row][7] = helper.getFileLengthDescByKB(file.getLen());
		}
		m[row][4] = file.getPath().toString();
		m[row][5] = file.getPath().getParent().toString();
		CalendarEx cal = new CalendarEx(file.getModificationTime() / 1000, 0);
		m[row][6] = cal.toString(0);
	}

	/**
	 * tablePanel的右键菜单事件监听
	 */
	private ActionListener popupTableListener() {
		return e -> {
            if (table.getSelectedRow() < 0)
                return;
            final String strAction = ((JMenuItem) e.getSource()).getText().trim();

            switch (strAction) {
                case "删除":
                    deleteFile();
                    break;
                case "重命名":
                    renameHdfsFile();
                    break;
                case "剪切":
                    cpAndMvOperationOfTablePanel(false);
                    break;
                case "复制":
                    cpAndMvOperationOfTablePanel(true);
                    break;
                case "新建文件夹":
                    createNewDir();
                    break;
                case "归并压缩下载": {
                    JFileChooser fileChooser = new JFileChooser();
                    fileChooser.setDialogTitle("请选择目的文件夹");
                    fileChooser.setApproveButtonText("确定");
                    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                    int result = fileChooser.showOpenDialog(null);

                    if (JFileChooser.APPROVE_OPTION == result) {
                        final String localPath = fileChooser.getSelectedFile().getPath();
                        for (int row : table.getSelectedRows()) {
                            getTableInfoByRow(row);// 提取 tempPath, tempIsDir
                            final String hdfsPath = tempPath; // 防止多线程改了 tempPath
                            if (strAction.equals("归并压缩下载")) {
                                helper.mergeDown(hdfsPath, localPath + "/" + tempFileName);
                            }
                        } // end for
                    } // end if

                    break;
                }
                case "粘贴":
                    copyToHdfs();
                    break;
                case "从HDFS下载":
                case "下载5MB": {
                    JFileChooser fileChooser = new JFileChooser();
                    fileChooser.setDialogTitle("请选择目的文件夹");
                    fileChooser.setApproveButtonText("确定");
                    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                    int result = fileChooser.showOpenDialog(null);

                    if (JFileChooser.APPROVE_OPTION == result) {
                        final String localPath = fileChooser.getSelectedFile().getPath();
                        for (int row : table.getSelectedRows()) {
                            getTableInfoByRow(row);// 提取 tempPath, tempIsDir
                            if (tempIsDir && strAction.equals("下载5MB...")) {
                                // JOptionPane.showMessageDialog(null, tempPath+"不是文件\n请选择文件，而非目录！");
                                CustomDialog.show(tempPath + "不是文件\n请选择文件，而非目录！");
                                continue;
                            }
                            final String hdfsPath = tempPath; // 防止多线程改了 tempPath
                            if (strAction.equals("下载5MB")) {
                                helper.down5MFile(hdfsPath, localPath);
                            } else {
                                if (tempIsDir) {
                                    helper.downDir(hdfsPath, localPath);
                                } else {
                                    helper.downFile(hdfsPath, localPath);
                                    // DistributedFileSystem dfs = (DistributedFileSystem) hdfs.fs;
                                }
                            } // end if
                        } // end for
                    } // end if

                    break;
                }
                case "预览":
                    for (int row : table.getSelectedRows()) {
                        getTableInfoByRow(row);// 提取 tempPath, tempIsDir
                        if (tempIsDir) {
                            CustomDialog.show("不能预览，因为" + tempPath + "是文件夹");
                            continue;
                        }
                        helper.previewFile(tempPath);
                    }
                    break;
                case "复制完整名称":
                    for (int row : table.getSelectedRows()) {
                        getTableInfoByRow(row);// 提取 tempPath, tempIsDir
                        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(tempPath),
                                null);
                    }
                    break;
                case "复制表信息":

                    String fileInfo = "";
                    for (int j : table.getSelectedRows()) {
                        getTableInfoByRow(j);
                        fileInfo += tempFileName + "\t" + tempFilesize + "\t" + tempDir + "\t" + tempFileDate + "\n";
                    }
                    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(fileInfo), null);
                    break;
                case "返回上一级":

                    int row = table.getSelectedRow();
                    getTableInfoByRow(row);// 提取 tempPath

                    try {
                        Path grandParent = new Path(tempPath).getParent().getParent();
                        if (grandParent == null) {
                            CustomDialog.show("已经达到最顶层！！！");
                            return;
                        }
                        helper.executeCmd(new GotoPathCmd(grandParent.toString(), helper));
                    } catch (IllegalArgumentException e1) {
                        log.error(e1);
                    }
                    break;
                case "上传文件": {
                    JFileChooser fileChooser = new JFileChooser();
                    fileChooser.setDialogTitle("请选择要上传的文件");
                    fileChooser.setApproveButtonText("确定");
                    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    fileChooser.setMultiSelectionEnabled(true);
                    int result = fileChooser.showOpenDialog(null);
                    if (JFileChooser.APPROVE_OPTION == result) {
                        final File[] files = fileChooser.getSelectedFiles();
                        for (final File file : files) {
                            if (file.isFile()) {
                                helper.uploadFile(file.getPath(), helper.getNavigationPath());
                            }
                        }
                    }

                    break;
                }
                case "解压上传文件": {
                    JFileChooser fileChooser = new JFileChooser();
                    fileChooser.setDialogTitle("请选择要上传的文件");
                    fileChooser.setApproveButtonText("确定");
                    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    fileChooser.setMultiSelectionEnabled(true);
                    int result = fileChooser.showOpenDialog(null);
                    if (JFileChooser.APPROVE_OPTION == result) {
                        final File[] files = fileChooser.getSelectedFiles();
                        for (final File file : files) {
                            if (file.isFile()) {
                                helper.uncompressUpload(file.getPath().toString(), helper.getNavigationPath());
                            }
                        }
                    }
                    break;
                }
                case "上传文件夹": {
                    JFileChooser fileChooser = new JFileChooser();
                    fileChooser.setDialogTitle("请选择要上传的目录");
                    fileChooser.setApproveButtonText("确定");
                    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                    fileChooser.setMultiSelectionEnabled(true);

                    int result = fileChooser.showOpenDialog(null);
                    if (JFileChooser.APPROVE_OPTION == result) {
                        final File[] files = fileChooser.getSelectedFiles();

                        for (File file : files) {
                            if (file.isDirectory())
                                helper.uploadDir(file.getPath().toString(),
                                        helper.getNavigationPath() + "/" + file.getName());
                        }
                    }
                    break;
                }
                case "归并上传文件夹": {
                    JFileChooser fileChooser = new JFileChooser();
                    fileChooser.setDialogTitle("请选择要上传的目录");
                    fileChooser.setApproveButtonText("确定");
                    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                    fileChooser.setMultiSelectionEnabled(true);

                    int result = fileChooser.showOpenDialog(null);
                    if (JFileChooser.APPROVE_OPTION == result) {
                        final File[] files = fileChooser.getSelectedFiles();

                        for (File file : files) {
                            if (file.isDirectory())
                                helper.mergeUpload(file.getPath(),
                                        helper.getNavigationPath(), file.getName());
                        }
                    }
                    break;
                }
                case "添加SUCCESS标志文件": {
                    for (int aRow : table.getSelectedRows()) {
                        getTableInfoByRow(aRow);// 提取 tempPath, tempIsDir
                        helper.createSuccessFile(tempPath);
                    }
                    break;
                }
                case "合并小文件": {
                    List<FileStatus> filePaths = new LinkedList<>();
                    int[] rows = table.getSelectedRows();
                    if (rows.length > 1) {
                        CustomDialog.show("当前不支持不同文件夹下的文件合并，如果你有此需求，请先将文件移到同一目录");
                        break;
                    }
                    for (int aRow : table.getSelectedRows()) {
                        getTableInfoByRow(aRow);// 提取 tempPath, tempIsDir
                        FileStatus[] statuses = helper.listStatus(tempPath);
                        filePaths.addAll(Arrays.asList(statuses));
                    }
                    helper.concat(filePaths.toArray(new FileStatus[0]));
                    break;
                }
                case "过滤": {
                    filterSpark();
                    break;
                }
                case "批量重命名该文件夹下文件": {
                    int aRow = table.getSelectedRow();
                    getTableInfoByRow(aRow);
                    FileStatus[] statuses = helper.listStatus(tempPath);
                    helper.batchRenameFile(statuses);
                    break;
                }
            }
        };
	}

	/**
	 * 表格面板的复制剪切操作
	 * 
	 * @param isCopy
	 *            不是复制操作就是剪切操作
	 */
	private void cpAndMvOperationOfTablePanel(boolean isCopy) {
		String clipboard = isCopy ? "cp" : "mv";

		for (int row : table.getSelectedRows()) {
			getTableInfoByRow(row);// 提取 tempPath, tempIsDir
			clipboard += tempPath + "\n";
		}

		Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(clipboard), null);
	}

	/**
	 * 粘贴文件
	 */
	private void copyToHdfs() {
		for (int row : table.getSelectedRows()) {
			getTableInfoByRow(row);// 提取 tempPath, tempIsDir
			
				helper.pasteFile(tempPath);
		
		}
		helper.refresh();
	}
	
	private void createNewDir() {
		
		for (int row : table.getSelectedRows()) {
			getTableInfoByRow(row);// 提取 tempPath, tempIsDir
			Object[] options = { "确定", "取消" };

			JPanel contentPanel = new JPanel();
			contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
			contentPanel.setLayout(null);

			JLabel label = new JLabel("请输入子目录的名称");
			label.setBounds(10, 23, 125, 15);
			contentPanel.add(label);

			JTextField tfSubFoldName = new JTextField();
			tfSubFoldName.setBounds(20, 48, 350, 21);
			contentPanel.add(tfSubFoldName);
			tfSubFoldName.setColumns(10);
			contentPanel.setPreferredSize(new Dimension(100, 88));
			if (label != null)
				label.setText("请输入子目录的名称");

			int answer = JOptionPane.showOptionDialog(null, contentPanel, "创建子目录", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[1]);
			if (answer == 0) {
				helper.createDir(tempPath + "/" + tfSubFoldName.getText().trim());
			}
		
		}
		helper.refresh();	
	}

    /**
     * 过滤文件
     */
    protected void filterSpark() {
        for (int row : table.getSelectedRows()) {
            getTableInfoByRow(row);// 提取 tempPath, tempIsDir
            Object options[] = { "确定", "取消" };

            JPanel contentPanel = new JPanel();

            contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
            contentPanel.setLayout(null);

            JLabel label = new JLabel("要过滤的路径：");
            label.setBounds(10, 30, 100, 15);
            contentPanel.add(label);

            JTextField tfSubFoldName = new JTextField();
            tfSubFoldName.setBounds(120, 25, 350, 21);

            contentPanel.add(tfSubFoldName);
            tfSubFoldName.setText(tempPath);


            JLabel label2 = new JLabel("请输入分离符：");
            label2.setBounds(10, 80, 100, 15);
            contentPanel.add(label2);
            String str1[] = {"\\t",",","_"};
            jcb = new JComboBox(str1);
            jcb.setEditable(true);
            jcb.setBounds(120, 75, 350, 21);
            contentPanel.add(jcb);

            JLabel label3 = new JLabel("输入sql语句：");
            label3.setBounds(10, 130, 100, 15);
            contentPanel.add(label3);
            JTextArea textArea = new JTextArea();
            textArea.setBounds(120, 125, 350, 100);
            textArea.setLineWrap(true);
            contentPanel.add(textArea);
            if(tempFileName.contains("-")){
                textArea.setText("select * from tb_mt_" + tempFileName.replace('-', '_') );
            }
            else{
                textArea.setText("select * from tb_mt_" + tempFileName);
            }
            JLabel label4 = new JLabel("要输出的路径：");
            label4.setBounds(10, 255, 100, 15);
            contentPanel.add(label4);
            JTextField tfSubFoldName4 = new JTextField();
            tfSubFoldName4.setBounds(120,250, 350, 21);
            contentPanel.add(tfSubFoldName4);
            tfSubFoldName4.setColumns(10);

            contentPanel.setPreferredSize(new Dimension(500,300));
            int answer = JOptionPane.showOptionDialog(null, contentPanel, "过滤", 0, -1, null, options, options[1]);
            if (answer == 0) {
                helper.filterSpark(tfSubFoldName.getText(),jcb.getSelectedItem().toString(),textArea.getText(),tfSubFoldName4.getText());
            }
        }
        helper.refresh(tempParentPath);
    }
	
	/**
	 * 重命名文件
	 */
	private void renameHdfsFile() throws HeadlessException {
		for (int row : table.getSelectedRows()) {
			getTableInfoByRow(row);// 提取 tempPath, tempIsDir
			Object options[] = { "确定", "取消" };

			JPanel contentPanel = new JPanel();
			contentPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
			contentPanel.setLayout(null);

			JLabel label = new JLabel("请输入" + tempFileName + "的新名称");
			label.setBounds(10, 23, 500, 15);
			contentPanel.add(label);

			/*JTextField tfSubFoldName = new JTextField();
			tfSubFoldName.setBounds(20, 48, 650, 21);
			contentPanel.add(tfSubFoldName);
			tfSubFoldName.setColumns(10);
			tfSubFoldName.setText(tempFileName);*/
			JTextArea text=new JTextArea(20,40);
			text.setText(tempFileName);
			JScrollPane scroll=new JScrollPane(text);
			scroll.setBounds(10, 50, 500, 30);
scroll.setSize(500,20);
scroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setVerticalScrollBarPolicy( 
		 
JScrollPane.VERTICAL_SCROLLBAR_NEVER);
			contentPanel.add(scroll);
			contentPanel.setPreferredSize(new Dimension(500,70));

			int answer = JOptionPane.showOptionDialog(null, contentPanel, "重命名", 0, -1, null, options, options[1]);
			if (answer == 0) {
				helper.renameFile(tempPath, tempParentPath + "/" + text.getText());
			}
		}
		helper.refresh(tempParentPath);
	}

	private void deleteFile() {
		int n = JOptionPane.showConfirmDialog(null, "确认删除所选文件吗？", "确认删除框", JOptionPane.YES_NO_OPTION);
		if (n == JOptionPane.NO_OPTION) {
			return;
		}
		for (int row : table.getSelectedRows()) {
			getTableInfoByRow(row);// 提取 tempPath, tempIsDir
			try {
				helper.deleteFile(tempPath);
			} catch (Exception e1) {
				CustomDialog.show(tempPath + "删除");
			}
		}
		helper.refresh();
	}

	/**
	 * 表格过滤（支持正则表达式）
	 */
	private void filterRow(String filter) {
		
		if (filter == null) return;
		
		@SuppressWarnings("unchecked")
		TableRowSorter<TableModel> sorter = (TableRowSorter<TableModel>) table.getRowSorter();

		sorter.setRowFilter(RowFilter.regexFilter(filter));

		// 统计过滤后的表格信息
		long totalSize = 0;
		for (int i = 0; i < table.getRowCount(); i++) {
			totalSize += Double.parseDouble(getValue(i, 7));
		}
		
		filterDetail
				.setText("共" + table.getRowCount() + "个文件，总大小为" + helper.getFileLengthDesc((long) totalSize * 1024));
	}

	@Override
	public void update(Observable o, Object arg) {
		if (o instanceof HdfsExplorerHelper) {
			if (arg instanceof String) {
				FileStatus[] fileStatus = ((HdfsExplorerHelper) o).listStatus((String) arg);
				refreshTable(fileStatus);
				if (filterField.getText()!=null)
					filterRow(filterField.getText());
			}
		}
	}

	/**
	 * 为了防止调用<code>hashCode</code>方法可能引起循环依赖的问题，因此必须重写<code>hashCode</code>方法
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((table == null) ? 0 : table.hashCode());
		return result;
	}

	/**
	 * 重写了<code>hashCode</code>方法，因此也必须重写<code>equals</code>方法
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		TablePane other = (TablePane) obj;
		if (table == null) {
			if (other.table != null)
				return false;
		} else if (!table.equals(other.table))
			return false;
		return true;
	}

}
